#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "mqmclient.hpp"

using namespace topconn;

static size_t  getFilesize(FILE* hFile)
{
	long nFileLen = 0;
	if(hFile == NULL) return -1;
	long nCurPos = ftell(hFile);
	fseek(hFile, 0, SEEK_END);
	nFileLen = ftell(hFile);
	fseek(hFile, nCurPos, SEEK_SET);	
	return nFileLen;
}

void Usage(int argc,char* argv[])
{
    printf("Usage1:%s qmName qName qMsgfile \n",argv[0]);
    printf("Usage2:%s qmName qName qMsgfile qConnectName qChannel(default:SYSTEM.DEF.SVRCONN) \n",argv[0]);
    return;
}

int QSend(const char* psQMName,const char* psQName,const char* psConnectName,const char* psChannel,char* sContext)
{
    MqmClient mqClient;
    mqClient.setQmName(psQMName);
    mqClient.setQConnectName(psConnectName);
    mqClient.setQChannel(psChannel);
    mqClient.setQname(psQName);
    if(mqClient.connect() != 0)
    {
        printf("connect error! ThreadID [%ld] exit.\n",  pthread_self());
        return -1;
    }
    if (mqClient.openQueue() != 0)
    {
        printf("openQueue error! ThreadID [%ld] exit.\n", pthread_self());
        return -1;
    }

    if( mqClient.put(sContext) != 0 )
    {
        printf("put error! ThreadID [%ld] exit.\n",  pthread_self());
        return -1;
    }
    return 0;
}

int main(int argc,char* argv[])
{
    if(argc != 4 && argc != 5 && argc != 6)
    {
        Usage(argc,argv);
        return -1;
    }
    
    char sQMName[40] = {0};
    char sQName[40] = {0};
    char sQMsgfile[128] = {0};
    char sQChannel[40] = {0};
    char sQConnectName[80] = {0};

    strcpy(sQMName,argv[1]);
    strcpy(sQName,argv[2]);
    strcpy(sQMsgfile,argv[3]);

    if(argc == 5)
    {
        strcpy(sQConnectName,argv[4]);
        strcpy(sQChannel, "SYSTEM.DEF.SVRCONN");
    }
    else if(argc == 6)
    {
        strcpy(sQConnectName,argv[4]);
        strcpy(sQChannel,argv[5]);
    }   

    FILE* fp_qmsgfile = fopen(sQMsgfile,"r");
    if(fp_qmsgfile == NULL)
    {
        printf("fopen file [%s] error:%s\n",sQMsgfile,strerror(errno));
        return -1;
    }

    long nFileSize = getFilesize(fp_qmsgfile);
    if(nFileSize == 0)
    {
        fclose(fp_qmsgfile);
        printf("QMSGFILE SIZE IS EMPTY\n");
        return -1;
    }

    char* QMsgText = (char*) calloc(nFileSize+1,1);
    if(QMsgText == NULL)
    {
        fclose(fp_qmsgfile);
        printf("calloc() error:%s\n",strerror(errno));
        return -1;
    }
	fread(QMsgText, nFileSize, 1, fp_qmsgfile);
	QMsgText[nFileSize] = 0x00;    

    printf("QMsgText=[%s]\n",QMsgText);

    fclose(fp_qmsgfile);
    return QSend(sQMName,sQName,sQConnectName,sQChannel,QMsgText);
}